package 栈的数组实现;

import java.util.Iterator;

public class Stack2<E> implements Iterable<E>{

    private int top;
    private final int capacity;
    private final E[] array;

    @SuppressWarnings("all")
    public Stack2(int capacity) {
        array = (E[]) new Object[capacity];
        this.capacity = capacity;
    }

    /**
     * 向栈顶压入元素
     *
     * @param value 带压入值
     * @return 压入成功返回true, 否则返回false
     */
    public boolean push(E value) {
        if (isFull()) {
            return false;
        }
        array[top] = value;
        top++;
        return true;
    }

    /**
     * 从栈顶弹出元素
     *
     * @return 栈非空返回栈顶元素, 栈为空返回null
     */
    public E pop() {
        if (isEmpty()) {
            return null;
        }
        return array[--top];
    }

    /**
     * 返回栈顶元素, 不弹出
     *
     * @return 栈非空返回栈顶元素, 栈为空返回null
     */
    public E peek() {
        if (isEmpty()) {
            return null;
        }
        return array[top - 1];
    }

    /**
     * 判断栈是否为空
     *
     * @return 空返回true, 否则返回false
     */
    boolean isEmpty() {
        return top == 0;
    }

    /**
     * 判断栈是否为满
     *
     * @return 满返回true, 否则返回false
     */
    Boolean isFull() {
        return top == capacity;
    }

    @Override
    public Iterator<E> iterator() {
        return new Iterator<>() {
            int p = top;

            @Override
            public boolean hasNext() {
                return p != 0;
            }

            @Override
            public E next() {
                return array[--p];
            }
        };
    }
}
